package com.chang.product.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chang.common.utils.PageUtils;
import com.chang.common.utils.Query;
import com.chang.product.entity.BrandEntity;
import com.chang.product.mapper.BrandDao;
import com.chang.product.service.BrandService;
import com.chang.product.service.CategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        // 获取模糊查询字段
        String key = (String) params.get("key");
        QueryWrapper<BrandEntity> wrapper = new QueryWrapper<>();
        if (StringUtils.hasLength(key)) {
            wrapper.eq("brand_id", key)
                    .or()
                    .like("name", key);
        }
        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    @Override
    public void updateDeleted(BrandEntity brand) {
        baseMapper.updateDeleted(brand);
    }

    // 逻辑删除查询 参数传递已完善
    @Override
    public PageUtils selectDeleted(Map<String, Object> params) {

        IPage<BrandEntity> page = this.page(new Query<BrandEntity>().getPage(params), new QueryWrapper<>());

        List<BrandEntity> brandEntities = baseMapper.selectDeleted();
        // 使用自定义sql获取的list对象来覆盖原本被逻辑删除插件拦截的残缺数据
        page.setRecords(brandEntities);
        page.getRecords().forEach(System.out::println);

        return new PageUtils(page);
    }

    @Override
    public void finalDelete(List<Long> list) {
        baseMapper.finalDelete(list);
    }

    /*
     * @Author Chang
     * @Date 2024/3/6 9:46
     * @Description 品牌进行更新的时候关联表(CategoryBrandRelation)的字段属性也需要同步更新
     * 关联表是用来关联品牌和产品的 比如小米品牌的手机
     * @Param [brand]
     * @Return void
     * @Since version 1.0
     */
    @Override
    @Transactional
    public void updateDetail(BrandEntity brand) {
        // 首先更新自身
        this.updateById(brand);
        // 判断品牌名是否有值,有则同步更新
        if (StringUtils.hasLength(brand.getName())) {
            categoryBrandRelationService.updateBrand(brand.getBrandId(), brand.getName());
        }
    }

}